package personal.dao.accounting;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import personal.dao.support.HibernatePropertyReader;
import personal.domain.accounting.WeeklyBalance;


@Repository
public class WeeklyBalanceDAOImpl implements WeeklyBalanceDAO {
	
	@PersistenceContext(unitName="accountingPU")
	private EntityManager em;
	private HibernatePropertyReader hibernatePropertyReader;

	public HibernatePropertyReader getHibernatePropertyReader() {
		return hibernatePropertyReader;
	}

	@Autowired(required=false)
	public void setHibernatePropertyReader(HibernatePropertyReader hibernatePropertyReader) {
		this.hibernatePropertyReader = hibernatePropertyReader;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<WeeklyBalance> getAllWeeklyBalances() {
		return em.createNamedQuery(WeeklyBalance.WEEKLY_BAL_GET_ALL_NAMED_QUERY)
					.getResultList();
	}

	@Override
	public void saveWeeklyBalance(WeeklyBalance wBalance) {
		em.merge(wBalance); //inserts or updates the balance and manages the instance
	}

	/**
	 * Saves (insert or update) a list of weekly balances in batches depending upon hibernate.jdbc.batch_size.
	 * If batch size is not specified, saves one at a time.
	 * @param wBalances - List<WeeklyBalance>
	 */
	@Override
	public void saveWeeklyBalances(List<WeeklyBalance> wBalances) {
		int batchSize = getBatchSize();
		for(int i=0; i < wBalances.size(); i++) {
			saveWeeklyBalance(wBalances.get(i));
			if ((i+1)%batchSize == 0) { //flush every 20 records
				em.flush();
			}
		}
	}

	@Override
	public void deleteWeeklyBalance(String wBalanceDesc) {
		WeeklyBalance wBalance = em.getReference(WeeklyBalance.class, wBalanceDesc);
		em.remove(wBalance);

	}

	@Override
	public void deleteWeeklyBalances(List<String> wBalances) {
		Query query = em.createNamedQuery(WeeklyBalance.WEEKLY_BAL_DEL_MULTIPLE_NAMED_QUERY);
		query.setParameter("descriptions", wBalances);
		query.executeUpdate();
	}
	
	/**
	 * Returns jdbc batch size from hibernate configuration
	 * @return int - Batch size
	 */
	private int getBatchSize() {
		String batchSize = hibernatePropertyReader.getProperty("hibernate.jdbc.batch_size");
		if (batchSize == null) return 1;
		else return Integer.parseInt(batchSize);
	}
}
